<?php

namespace addons\sdcmarry\controller\api;

use addons\sdcmarry\library\MPLib;
use addons\sdcmarry\library\Service;
use addons\sdcmarry\library\WXBizDataCrypt;
use app\common\model\User as ModelUser;
use fast\Date;
use think\Cache;
use think\Db;
use think\Validate;

class User extends Api
{
    protected $noNeedLogin = ['third'];
    protected $noNeedRight = ['*'];

    private $model = null;
    private $extendUser = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ModelUser();
    }

    public function third()
    {
        $code = $this->request->request("code");
        $avatarUrl = $this->request->request('avatarUrl');
        $nickName = $this->request->request('nickName');
        $config = get_addon_config('sdcmarry');
        if (!$config || !isset($config['mp'])) {
            $this->error(__('Invalid parameters'));
        }
        $MPLib = new MPLib($config['mp']);
        $result = $MPLib->getLoginInfo(['code'=>$code]);
        if ($result) {
            $result['userinfo'] = [
                'avatar' => $avatarUrl,
                'nickname' => $nickName
            ];
            // dump($result);
            $loginret = Service::connect('mp', $result);
            if ($loginret) {
                $userinfo =  $this->auth->getUserinfo();
                $data = [
                    'userinfo'  => $userinfo,
                ];
                
                Cache::set('mp_session_'.$userinfo['id'],$result,Date::DAY * 7);
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'));
    }

     // 微信自动绑定手机号
     public function mpchangemobile()
     {
         $userInfo = $this->auth->getUserinfo();
         $cacheKey = 'mp_session_'.$userInfo['id'];
         if(! Cache::has($cacheKey)){
             $this->error(__('Session key must required'));
         }
         $encryptedData = $this->request->post('encryptedData');
         if(! Validate::checkRule($encryptedData,'require')){
             $this->error(__('encryptedData must required'));
         }
         $iv = $this->request->post('iv');
         if(! Validate::checkRule($iv,'require')){
             $this->error(__('iv must required'));
         }
         $config = get_addon_config('sdcmarry');
         $cacheSession = Cache::get($cacheKey);
         
         $appid = $config['mp']['app_id'];
         $sessionKey = $cacheSession['session_key'];
         
         $pc = new WXBizDataCrypt($appid, $sessionKey);
         $errCode = $pc->decryptData($encryptedData, $iv, $data );
         
         if ($errCode != 0) {
             $this->error(__('Mobile bind error'));
 
         }         
         $result = json_decode($data,true);
         $user = $this->auth->getUser();
         $user->mobile = $result['phoneNumber'];
         $user->save();
         $this->success(__('Mobile bind success'),$result);
     }

     // 读取用户预约的订单
     public function orders()
     {
         $user = $this->auth->getUser();
         $result = Db::table('__SDCMARRY_ORDER__')
                    ->alias('order')
                    ->join('__USER__ user','user.id = order.user_id')
                    ->field('order.*')
                    ->where('user.id',$user->id)
                    ->order('order.id','DESC')
                    ->paginate(4);
        $this->success('Request success',$result);
     }
}